import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import "./css/RoleFunAuth.less";
import {addOkModal, closeModal} from "../../../services/ModalService";
import {AxiosGet, AxiosSer} from "../../../services/HttpService";
import {Input, Tree} from "antd";
import useStateRef from "../../../customUse/useStateRef";
import {getLocale} from "../../../../i18n/i18n";
import useThrottle from "../../../customUse/useThrottle";
import {createFetchParams} from "../../../utils";

interface RoleFunAuthProps {
    modalKey: string,
    flowData: any[],
}

const RoleFunAuth: FC<RoleFunAuthProps> = (props) => {
    const roleAuthRef = useRef([]);
    const roleSelectRef = useRef([]);

    const [roleAuth, setRoleAuth] = useState<any[]>(),
        [roleSelectKeys, setRoleSelectKeys] = useStateRef([], roleSelectRef);

    const onOk: Function = useThrottle(async () => {
        if (!roleSelectRef.current) {
            return;
        }
        const {flowData = []}: { flowData: any[] } = props,
            fetchParams: any = createFetchParams(props)
        let params: any = {
            ...fetchParams.params,
            objectId: flowData[0].id,
            presetRoles: [...roleSelectRef.current]
        }
        let result: any = await AxiosSer("/sf-drs/platform/funcGrant/grantPresetRole", "POST", params) || {};
        result.code == "1" && await closeModal(props.modalKey, async () => {
            return {data: params, ...result};
        })
    }, 2000, []);

    const initRoleAuth = useCallback(async () => {
        const {flowData = []}: { flowData: any[] } = props;
        if (flowData[0]) {
            const {data = []}: {
                data: any[]
            } = await AxiosGet("/sf-drs/platform/presetRole/getPresetRolesByAccessor", {accessorId: flowData[0].id});
            let selectKeys: string[] = [];
            const newRoleAuth = data.map((item: any) => {
                if (item.isGrant) {
                    selectKeys.push(item.id);
                }
                return {
                    ...item,
                    title: getLocale(item.zhCn, item.usEn, item.ptBr)
                }
            });
            roleAuthRef.current = newRoleAuth;
            setRoleAuth(newRoleAuth);
            setRoleSelectKeys(selectKeys);
        }

    }, []);

    useEffect(() => {
        initRoleAuth()
    }, [props.flowData]);

    useEffect(() => {
        addOkModal(props.modalKey, onOk);
    }, []);

    const handleSearch = useCallback((value: any) => {
        if (roleAuthRef.current) {
            let newRoleAuth: any[] = roleAuthRef.current.filter((n: any) => (n.title.indexOf(value) !== -1));
            setRoleAuth(newRoleAuth);
        }
    }, []);

    const handleCheck = useCallback((checkedKeys: string[]) => {
        setRoleSelectKeys(checkedKeys);
    }, []);

    const renderRoleFunAuth = useMemo(() => {
        if (!roleAuth) {
            return null
        }
        return (
            <div className="sf_core_role_fun_auth">
                <Input.Search onSearch={handleSearch}/>
                <Tree
                    checkable
                    blockNode
                    treeData={roleAuth}
                    onCheck={handleCheck}
                    checkedKeys={roleSelectRef.current}
                    fieldNames={{key: "id"}}
                />
            </div>
        )
    }, [roleAuth, roleSelectKeys]);

    return (renderRoleFunAuth);
}

export default React.memo(RoleFunAuth);